package com.moon.interface_api.controller;

import com.moon.interface_api.constansts.MsgConstants;
import com.moon.interface_api.domain.UserDO;
import com.moon.interface_api.enums.ResultEnum;
import com.moon.interface_api.response.BaseResponse;
import com.moon.interface_api.response.Result;
import com.moon.interface_api.service.LoginService;
import com.moon.interface_api.service.UserService;
import com.moon.interface_api.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private LoginService loginService;
    
    @Autowired
    private RedisTemplate redisTemplate;
    
  

    @ResponseBody
    @RequestMapping(value = "/login", method = {RequestMethod.POST, RequestMethod.GET})
    public Result list(@RequestBody Map<String, String> params){
        
        //判断验证码是否正确
        String code = redisTemplate.opsForValue().get(MsgConstants.PREFIX_LOGIN + params.get("phoneNum")).toString();
        if(params.get("code") == null || !code.equalsIgnoreCase(params.get("code"))){
            return Result.error(ResultEnum.CODE_ERROR.getCode(),ResultEnum.CODE_ERROR.getMsg());
        }

        Map<String, Object> userMap = new HashMap<>();
        String phoneNum = params.get("phoneNum");
        userMap.put("phoneNum",phoneNum);
        //查看是否新用户
        List<UserDO> list = userService.list(userMap);
        //token
        String token;
        
        if(list.size() == 0){
            //新用户
            UserDO userDO = new UserDO();
            userDO.setCreateTime(new Date());
            userDO.setPhoneNum(params.get("phoneNum"));
            userService.save(userDO);
        }
        //生成token
        token = TokenUtils.createToken(params.get("phoneNum") + "," + new Date().getTime());
        HashMap<String, Object> listParams = new HashMap<>();
        listParams.put("phoneNum",phoneNum);
        List<UserDO> userList = userService.list(listParams);
        UserDO userDO = userList.get(0);
        //判断是否有账号
        
        redisTemplate.opsForValue().set("token_"+params.get("phoneNum"),token,MsgConstants.TOKEN_LIVE_TIME, TimeUnit.SECONDS);
        userMap.put("token",token);
        new HashMap<String,String>();
        return Result.success(userMap);
    }


    @RequestMapping(value="/sendCode", method = RequestMethod.POST)
    public BaseResponse sendCode(@RequestBody Map<String, String> params){
        BaseResponse baseResponse = new BaseResponse();
        //baseResponse = loginService.sendCode(params);
        return baseResponse;
    }
    
}
